package com.datastructure.practice;

public class Salvation {

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(2);
        listNode1.next=new ListNode(4);
        listNode1.next.next=new ListNode(3);
        listNode1.next.next.next=new ListNode(9);

        ListNode listNode2 = new ListNode(5);
        listNode2.next=new ListNode(6);
        listNode2.next.next=new ListNode(4);
        ListNode listNode = addTwoNumbers(listNode1, listNode2);
        listNode.list();
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2){
        ListNode pre = new ListNode(0);
        ListNode buffer = pre;
        int sum;
        int discuss = 0;
        int surplus;
        while(l1!=null&&l2!=null){
            sum = l1.val + l2.val + discuss;
            discuss = sum / 10;
            surplus = sum % 10;
            buffer.next = new ListNode(surplus);
            buffer = buffer.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        while (l1!=null){
            sum = l1.val + discuss;
            discuss = sum / 10;
            surplus = sum % 10;
            buffer.next = new ListNode(surplus);
            buffer = buffer.next;
            l1 = l1.next;
        }
        while (l2!=null){
            sum = l2.val + discuss;
            discuss = sum / 10;
            surplus = sum % 10;
            buffer.next = new ListNode(surplus);
            buffer = buffer.next;
            l2 = l2.next;
        }
        if(discuss==1){
            buffer.next = new ListNode(1);
        }
        return pre.next;
    }
}


class ListNode {
    int val;
    ListNode next;

    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public void list(){
        ListNode pre = this;
        while (pre!=null){
            System.out.println(pre.val);
            pre = pre.next;
        }
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
